import 'PackageInterface.dart';
import 'SendBean.dart';

//多组节目一起发送,多用于播放列表的发送
class MultipleSendBean extends SendBean {
  //待发送的数据
  final List<SendBean> _sendBeans = [];

  //获取数据包数量
  @override
  int getPackageCount() {
    int count = 0;
    for (var bean in _sendBeans) {
      count += bean.getPackageCount();
    }
    return count;
  }

  //添加数据包
  void addSendBean(SendBean package) {
    _sendBeans.add(package);
  }

  //添加数据包组
  void addSendBeans(List<SendBean> packages) {
    _sendBeans.addAll(packages);
  }

  //清空数据包组
  @override
  void clear() {
    _sendBeans.clear();
  }

  //发送失败
  @override
  void onSendError() {
    int tmpIndex = 0;
    for (var bean in _sendBeans) {
      if (tmpIndex + bean.getPackageCount() > index) {
        index = tmpIndex + bean.getPackageCount();
        return;
      }
      tmpIndex += bean.getPackageCount();
    }
  }

  ///获取下一个要发送的数据包
  @override
  PackageInterface? getNextPackage({int? index}) {
    index ??= this.index;
    if (index >= getPackageCount()) {
      return null;
    }
    int tmpIndex = 0;
    for (var bean in _sendBeans) {
      if (tmpIndex + bean.getPackageCount() > index) {
        var nextPackage = bean.getNextPackage(index: index - tmpIndex);
        return nextPackage;
      }
      tmpIndex += bean.getPackageCount();
    }
  }
}
